﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using Galaktika.BI.Runtime.Services;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime;
using Galaktika.BI.Silverlight.Controls;
using Galaktika.BI.Silverlight.Commands;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.DataAccess;
using Galaktika.BI.Silverlight.Services;
using Galaktika.BI.Extensibility.Dom.Dac;
using Ranet.Olap.Core.Providers.ClientServer;
using System.Text;

namespace Galaktika.BI.Silverlight.ClientApp.Web.Commands.PivotGrid
{
    public class UpdateCubeCommand : ServerCommand
    {
        public UpdateCubeCommand(InvokeSchema invoker)
            : base(Galaktika.BI.Silverlight.Commands.CommandId.UpdateCubeCommandId)
        {
            this.Schema = invoker;
            this.ContextId = invoker[KnownInvokeArgs.ContextId];
            this.DataSourceId = invoker[KnownInvokeArgs.DataSourceId];
            this.Args = XmlUtility.XmlStr2Obj<UpdateCubeArgs>(invoker[KnownInvokeArgs.UpdateCube]);
        }

        public InvokeSchema Schema { get; private set; }
        public string ContextId { get; private set; }
        public string DataSourceId { get; private set; }
        public UpdateCubeArgs Args { get; private set; }

        private IBindingContext Context
        {
            get
            {
                return DataBinder.Current.GetContext(this.ContextId);
            }
        }

        private OlapDataManager DataManager
        {
            get
            {
                IBindingManager bindingMgr = DataBinder.Current.GetBindingManager(this.ContextId, this.DataSourceId);
                if (bindingMgr != null)
                {
                    return bindingMgr.DataManager as OlapDataManager;
                }

                return null;
            }
        }

        public override InvokeResultSchema Invoke()
        {
            String script = DataManager.UpdateScript;
            // Парсинг запросов
            IExecutionContext exe = (IExecutionContext)Context.Services.GetService(typeof(IExecutionContext));
            if (exe != null)
            {
                script = exe.Parse(Context, script);

                //PivotTableUpdater.ParseHierarchies(ref script, this.Args.Entries[0].
                this.Schema.Args.Add(new InvokeArg(KnownInvokeArgs.UpdateScript, script));
                BrickDataSource ds = DataBinder.Current.GetNamedObject(this.DataSourceId) as BrickDataSource;
                if (ds != null)
                {
                    this.Args.ConnectionString = exe.Parse(Context, ds.Connection.ConnectionString);

                    if (App.CurrentApp.Binder.UserSettings.Settings.LogMdxQueries)
                    {
                        var sb = new StringBuilder();
                        var sessionId = this.Schema.AsDictionary[KnownInvokeArgs.SessionId];
                        foreach (var cmd in PivotTableUpdateParser.GetUpdateScripts(script, this.Args))
                        {
                            sb.Append(cmd);
                            sb.Append(Environment.NewLine);
                        }

                        var output = this.Context.Services.GetService<IOutputService>();
                        if (output != null)
                        {
                            output.WriteLine();
                            output.WriteLine(
                                Localization.Msg_ExecutingMdxCommand, 
                                this.Args.ConnectionString,
                                sessionId,
                                sb.ToString());
                        }
                    }

                    this.Schema[KnownInvokeArgs.UpdateCube] = XmlUtility.Obj2XmlStr(this.Args);
                    using (var srv = new SyncDataService())
                    {
                        var res = srv.InvokeCommand(this.Schema);
                        if (res.ContentType != KnownContentTypes.ADOMDError &&
                            res.ContentType != KnownContentTypes.Error)
                        {
                            AnalysisTransactionManager.SetHasPendingChanges(ds.Connection.Name);
                        }

                        return res;
                    }
                }
            }

            return new InvokeResultSchema(base.Id, "Unable to perform update command", KnownContentTypes.Error);
        }

        //private String DoUpdate(string args, MethodInvoker onComplete, MethodInvoker onError)
        //{
        //    String script = DataManager.UpdateScript;
        //    // Парсинг запросов
        //    IExecutionContext exe = (IExecutionContext)Context.Services.GetService(typeof(IExecutionContext));
        //    if (exe != null)
        //    {
        //        script = exe.Parse(Context, script);
        //        this.Schema.Args.Add(new InvokeArg(KnownInvokeArgs.UpdateScript, script));
        //    }
        //    MethodInvoker complete = onComplete;
        //    MethodInvoker error = onError;

        //    using (var srv = new SyncDataService())
        //    {
        //    }

        //    return PivotTableUpdater.UpdateSync(script, args, complete, error);
        //}

        //private void UpdateComplete()
        //{
        //}

        //private void UpdateError()
        //{
        //}
    }
}
